package org.imaginedays.androidall.appwidget;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.imaginedays.androidall.app.AndroidAllApp;

import android.content.Context;
import android.net.ConnectivityManager;
import android.util.Log;

/**
 * setting apn
 * 
 * @author imaginedays
 * 
 */
public class ApnICS {

	public ApnICS() {
	}

	public boolean getApnStatus(Context context) {
		boolean result = false;

		ConnectivityManager cMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		try {
			Method method = cMgr.getClass().getMethod("getMobileDataEnabled");
			method.setAccessible(true);
			result = (Boolean) method.invoke(cMgr);
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}
		return result;
	}

	public void setApnStatus(Context context, boolean isOn) {
		ConnectivityManager cMgr = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		try {
			Method method = cMgr.getClass().getMethod("setMobileDataEnabled",
					boolean.class);
			method.invoke(cMgr, isOn);
			// little trick
			for (int retry = 0; retry < 10; retry++) {
				Thread.sleep(100);
				if (getApnStatus(context) == isOn) {
					log("BREAKOUT at " + retry);
					break;
				}
			}

		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void log(String string) {
		Log.e(AndroidAllApp.TAG, "Apn ICS: " + string);
	}

}
